package com.ansion.exception;

import androidx.annotation.NonNull;

import com.ansion.basetool.BuildConfig;
import com.ansion.log.VLog;
import com.google.firebase.crashlytics.CustomKeysAndValues;
import com.google.firebase.crashlytics.FirebaseCrashlytics;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * Description:
 * <p>
 * Created by ____lamer on 2019-10-29 17:44
 */
public class ExceptionExtension {

    private static final boolean DEBUG = BuildConfig.DEBUG;
    private static final String TAG = "ExceptionExtension";

    /**
     * debug的时候我们应该抛出异常，以便及时发现问题
     * release的时候我们应该隐藏异常，最大可能不影响用户使用其他功能
     *
     * @param t 准备抛出的异常
     */
    public static void throwThrowable(Throwable t) {
        FirebaseCrashlytics.getInstance().recordException(t);

        if (VLog.OPEN_LOG) {
            VLog.e(TAG, t);
        }

        if (VLog.OPEN_LOG) {
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new RuntimeException(t);
            }
        }

    }

    /**
     * 接口报错只需要record，不需要throw exception
     * @param t
     */
    public static void recordThrowable(Throwable t) {
        FirebaseCrashlytics.getInstance().recordException(t);
    }

    /**
     * 添加新参数时务必更新https://algento.atlassian.net/wiki/spaces/BOT/pages/147161131/Firebase+Crashlytics
     * 参数超过64个后不会再保存新的参数
     * @param key 添加Crashlytics参数
     * @param value value
     */
    public static void setCustomKey(@NonNull String key,boolean value){
        FirebaseCrashlytics.getInstance().setCustomKey(key,value);
    }

    public static void setCustomKey(@NonNull String key,double value){
        FirebaseCrashlytics.getInstance().setCustomKey(key,value);
    }

    public static void setCustomKey(@NonNull String key,float value){
        FirebaseCrashlytics.getInstance().setCustomKey(key,value);
    }

    public static void setCustomKey(@NonNull String key,int value){
        FirebaseCrashlytics.getInstance().setCustomKey(key,value);
    }

    public static void setCustomKey(@NonNull String key,long value){
        FirebaseCrashlytics.getInstance().setCustomKey(key,value);
    }
    public static void setCustomKey(@NonNull String key,@NonNull String value){
        FirebaseCrashlytics.getInstance().setCustomKey(key,value);
    }

    public static void setCustomKey(@NonNull String key){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String date = sdf.format(new Date(System.currentTimeMillis()));
        FirebaseCrashlytics.getInstance().setCustomKey(key,date);
    }

    public static void setCustomKeys(@NonNull CustomKeysAndValues keysAndValues) {
        FirebaseCrashlytics.getInstance().setCustomKeys(keysAndValues);
    }
}
